<?php

/**
 * swolle处理进程同步房卡数据，以及发送短信
 * @modify songanwei 2016-02-01
 * @param object $worker
 * @return boolean
 */
function getCardTaskCallbackFunction($worker) {
    $fileLog = new \Org\Util\FileLog();
    while (true) {
        $data = $worker->read();
        $fileLog->write($data, 0, RUNTIME_PATH . "/Statistics/" . date('Y-m-d') . "_callback.log");
        if (!empty($data)) {
            $data = json_decode($data, true);
            $hotelId = $data['hotelId'];
            $oldOrderRooms = json_decode($data['old'], true);
            $newOrderRooms = json_decode($data['new'], true);
            $type = $data['type'];
            $hotelEntityModel = D('HotelEntity');
            $hotelEntity = $hotelEntityModel->getInfo($hotelId);
            if (!$hotelEntity) {
                $fileLog->write('hotel does not exist!', 0, RUNTIME_PATH . "/Statistics/" . date('Y-m-d') . "_callback.log");
                //释放数据
                continue;
            }
            //过滤数据,过滤手机号为空的数据，以及房间号为非锁掌柜的数据
            $roomInfoModel = D('RoomInfo');
            $roomInfos = $roomInfoModel->getInfoByHotel($hotelId, [ROOMFROM_QRM,ROOMFROM_RFANDQRM]);
            //获取锁掌柜的来源房间
            $qrcloudRoomNameArray = array_column($roomInfos, "name");
            $shareCardRecordModel = D('ShareCardRecord');
            //过滤数据
            foreach ($newOrderRooms as $key => &$newOrderRoom) {
                $newOrderRoom['startTime'] = $newOrderRoom['startdate'];
                $newOrderRoom['endTime'] = $newOrderRoom['enddate'];
                if (!in_array($newOrderRoom['roomName'], $qrcloudRoomNameArray)) {
                    unset($newOrderRooms[$key]);
                }
                $newOrderRoom['share'] = $shareCardRecordModel->getPidByOrderRoomId($newOrderRoom['orderRoomId']);
                if (!empty($newOrderRoom['share'])) {
                    $newOrderRoom['share'] = array_column($newOrderRoom['share'], 'potentialauthorityid');
                    $newOrderRoom['share'] = implode(',', $newOrderRoom['share']);
                }
            }
            unset($newOrderRoom);
            //过滤需要删除的数据
            foreach ($oldOrderRooms as $key => &$oldOrderRoom) {
                if (!in_array($oldOrderRoom['roomName'], $qrcloudRoomNameArray)) {
                    unset($oldOrderRooms[$key]);
                }
            }
            unset($oldOrderRoom);

            $communityNo = $hotelEntity['communityno'];
            Vendor('phpRPC.phprpc_client');
            $client = new \PHPRPC_Client(C('MANAGE_QRCLIENT_URL'));
            $client->setEncryptMode(3);
            $sendData = array(
                'flag' => 'uclbrt',
                'communityNo' => $communityNo,
                'time' => time(),
                'type' => $type,
                'new' => $newOrderRooms,
                'old' => $oldOrderRooms,
            );
            $result = $client->meizhuMakeCard($sendData);

            if(is_array($result) && $result['status'] == 200){
				if(!empty($data['IsBooking'])){
					continue;
				}
                //发送短信通知
                $sender = new \Org\Util\Sms();                
                $yunPianSender = new \Org\Util\yunPian();    
                $utc = new \Org\Util\UTC();            
                //新增短信通知
                if ($type == 0) {
                    $potentialAuthorityIdData = $result['data'];
                    foreach ($newOrderRooms as $newOrderRoom) {
                        if (!$newOrderRoom['mobile']) {
                            continue;
                        }
                        $noteSendMessage = !is_null($newOrderRoom['sendMessage']) && empty($newOrderRoom['sendMessage']);
                        $endTime = $newOrderRoom['endTime'];
                        if ($noteSendMessage) {
                            continue;
                        } elseif ($hotelEntity['universaltime_id'] != 5) {
                            $universalTimeModel = D('UniversalTime');
                            $universalTimeInfo = $universalTimeModel->field('timezone')->where(['id' => $hotelEntity['universaltime_id']])->find();
                            $endTime = $utc->toTimeZone($newOrderRoom['endTime'], $universalTimeInfo['timezone'], 'Asia/Shanghai');
                        }
                        //过期不发送短信
                        if (strtotime($endTime) < time()) {
                            continue;
                        }
                        $potentialAuthorityId = isset($potentialAuthorityIdData[$newOrderRoom['mobile']]) ? $potentialAuthorityIdData[$newOrderRoom['mobile']] : '';
                        if ($newOrderRoom['areacode'] == '86') {
                            $result = $sender->sendNoLoginCardMessage($newOrderRoom['mobile'], $newOrderRoom['roomName'], $newOrderRoom['startTime'], $newOrderRoom['endTime'], $potentialAuthorityId);
                        } else {
                            $result = $yunPianSender->sendNoLoginCardMessage($newOrderRoom['areacode'], $newOrderRoom['mobile'], $newOrderRoom['roomName'], $newOrderRoom['startTime'], $newOrderRoom['endTime'], $potentialAuthorityId);
                        }
                        $message = array(
                            "mobile" => $newOrderRoom['mobile'],
                            "areacode" => $newOrderRoom['areacode'],
                            'hotelName' => $hotelEntity['name'],
                            'roomName' => $newOrderRoom['roomName'],
                            'startTime' => $newOrderRoom['startTime'],
                            'endTime' => $newOrderRoom['endTime']
                        );
                        if ($result == false) {
                            //记录发送短信失败日志
                            $fileLog->write(json_encode($message), 1, RUNTIME_PATH . "/Statistics/Sms/" . date('Y-m-d') . "_error.log");
                        } else {
                            $fileLog->write(json_encode($message), 0, RUNTIME_PATH . "/Statistics/Sms/" . date('Y-m-d') . "_success.log");
                        }
                    }
                }
                //修改短信通知
                if ($type == 1) {
                    $potentialAuthorityIdData = $result['data'];
                    //比较手机号是否发生变化
                    foreach ($newOrderRooms as $newOrderRoom) {
                        if (!$newOrderRoom['mobile']) {
                            continue;
                        }
                        $noteSendMessage = !is_null($newOrderRoom['sendMessage']) && empty($newOrderRoom['sendMessage']);
                        $endTime = $newOrderRoom['endTime'];
                        if ($noteSendMessage) {
                            continue;
                        } elseif ($hotelEntity['universaltime_id'] != 5) {
                            $universalTimeModel = D('UniversalTime');
                            $universalTimeInfo = $universalTimeModel->field('timezone')->where(['id' => $hotelEntity['universaltime_id']])->find();
                            $endTime = $utc->toTimeZone($newOrderRoom['endTime'], $universalTimeInfo['timezone'], 'Asia/Shanghai');
                        }
                        //过期不发送短信
                        if (strtotime($endTime) < time()) {
                            continue;
                        }
                        $potentialAuthorityId = isset($potentialAuthorityIdData[$newOrderRoom['mobile']]) ? $potentialAuthorityIdData[$newOrderRoom['mobile']] : '';
                        if ($newOrderRoom['areacode'] == '86') {
                            $result = $sender->sendNoLoginCardMessage($newOrderRoom['mobile'], $newOrderRoom['roomName'], $newOrderRoom['startTime'], $newOrderRoom['endTime'], $potentialAuthorityId);
                        } else {
                            $result = $yunPianSender->sendNoLoginCardMessage($newOrderRoom['areacode'], $newOrderRoom['mobile'], $newOrderRoom['roomName'], $newOrderRoom['startTime'], $newOrderRoom['endTime'], $potentialAuthorityId);
                        }
                        $message = array(
                            "mobile" => $newOrderRoom['mobile'],
                            'hotelName' => $hotelEntity['name'],
                            'roomName' => $newOrderRoom['roomName'],
                            'startTime' => $newOrderRoom['startTime'],
                            'endTime' => $newOrderRoom['endTime']
                        );
                        if ($result == false) {
                            //记录发送短信失败日志
                            $fileLog->write(json_encode($message), 1, RUNTIME_PATH . "/Statistics/Sms/" . date('Y-m-d') . "_error.log");
                        } else {
                            $fileLog->write(json_encode($message), 0, RUNTIME_PATH . "/Statistics/Sms/" . date('Y-m-d') . "_success.log");
                        }
                    }
                }
            }else {
                $fileLog->write('create card failed!', 0, RUNTIME_PATH . "/Statistics/" . date('Y-m-d') . "_callback.log");                
            }
        }
    }
}

/**
 * 返回当前操作用户ID
 * @return int
 */
function getUserId() {
    //手机端操作用户Id
    if (MODULE_NAME == 'Mobile') {
        $userId = I('request.userId', 0, 'intval');
        return $userId;
    }
    //Web端操作用户ID
    return isset($_SESSION[C('USER_ID')]) ? $_SESSION[C('USER_ID')] : 0;
}
/**
 * 返回当前操作经销商ID
 * @return int
 */
function getDealerId() {
    return session(C('DEALER_ID'));
}
/**
 * 返回当前操作用户Name
 * @modify trainyao 2015-09-28 getUserName=>getUserNameFromSession
 * @modify AmosZhong 2015-10-08 修改为获取手机或者email
 * @return string
 */
function getUserName() {
    return session(C('USER_MOBILE')) ? session(C('USER_MOBILE')) : session(C('USER_EMAIL'));
}

/**
 * 分页
 * @param integer $count 分页总条数
 * @param $link 路由页面地址
 * @return \Think\Page
 */
function classpage($count, $link = '', $pageSize = null) {

    $pageSize =  is_null($pageSize) ? C('PAGE_SIZE') : $pageSize;
    $Page = new \Think\Page($count, $pageSize);
    $Page->setConfig('first', '<<');
    $Page->setConfig('last', '>>');
    $Page->setConfig('next', '>>');
    $count > C('PAGE_SIZE') ? $Page->setConfig('theme', '%FIRST% %LINK_PAGE% %END%') : '';
    if (!empty($link)) {
        $Page->setConfig('link', $link);
    }
    $Page->rollPage = C('MAX_PAGES'); //最后一页不显示为总页数
    $Page->lastSuffix = false; //最后一页不显示为总页数

    return $Page;
}

/**
 *
 * 检查访问权限
 * @modify songanwei 2016-01-27
 * @param type $access
 * @param type $accessString
 * @return boolean
 */
function checkAccess($access, $accessString) {
    if ($access['role'] == 1) {
        return true;
    }
    $accessArr = explode(',', $accessString);
    foreach ($accessArr as $string) {
        if (in_array($string, $access['access'])) {
            return true;
        }
    }
}

function cookieUserSSPS($userMobile, $hashPassword, $now) {
    $expireTime = $now + C('COOKIE_EXPIRE');
    return hash('sha512', $userMobile . substr($hashPassword, 0, C('COOKIE_SERVER_REMEMBER_ME_PASSWORD_LENGTH')) . $expireTime . C('COOKIE_SERVER_REMEMBER_ME_PASSPORT_HASH'));
}

function cookieDealerSSPS($userMobile, $hashPassword, $now) {
    $expireTime = $now + C('COOKIE_EXPIRE');
    return hash('sha512', $userMobile . substr($hashPassword, 0, C('COOKIE_SERVER_REMEMBER_DEALER_PASSWORD_LENGTH')) . $expireTime . C('COOKIE_SERVER_REMEMBER_DEALER_PASSPORT_HASH'));
}

/**
 * 生成订单号
 * @modify trainyao 2016-05-10 创建
 * @param  integer   $id        生成订单号凭证
 * @param  mixin   $channel   订单号渠道
 * @return string               订单号
 */
function encodeOrderNumber($id, $channel) {
    switch ($channel) {
        case 'MZ':
            return 'MZ' . ($id + C('MZ_ORDER_NUMBER_BASE'));
            break;
    }
}

/**
 * 订单号解密返回凭证
 * @modify trainyao 2016-05-10 创建
 * @param  string   $orderNumber        订单号
 * @param  mixin   $channel   订单号渠道
 * @return string               生成订单号凭证
 */
function decodeOrderNumber($orderNumber, $channel) {
    switch ($channel) {
        case 'MZ':
            return (int)substr($orderNumber, 2) - C('MZ_ORDER_NUMBER_BASE');
            break;
    }
}

/**
 * 生成优惠券号或用户领取号
 * @modify wenhui 2018-01-10 创建
 * @param  integer   $id        生成优惠券号或用户领取号凭证
 * @param  mixin   $channel  渠道
 * @return string               优惠券号或用户领取号
 */
function encodeCouponNumber($id, $channel) {
    switch ($channel) {
        case 'CP':
            return 'CP' . ($id + C('MZ_COUPON_NUMBER_BASE'));
            break;
         case 'UCP':
            return 'UCP' . ($id + C('MZ_GET_NUMBER_BASE'));
            break;
    }
}

/**
 * 优惠券号或用户领取号解密返回凭证
 * @modify wenhui 2018-01-10 创建
 * @param  integer   $id        生成优惠券号或用户领取号凭证
 * @param  mixin   $channel  渠道
 * @return string               优惠券号或用户领取号
 */
function decodeCouponNumber($no, $channel) {
    switch ($channel) {
        case 'CP':
            return (int)substr($no, 2) - C('MZ_COUPON_NUMBER_BASE');
            break;
        case 'UCP':
            return (int)substr($no, 3) - C('MZ_GET_NUMBER_BASE');
            break;
    }
}

/**
 * 改价记录
 * @modify zhangzhen 2017-03-28 创建
 * @param  int   $hotelId      酒店Id
 * @param  int   $roomType     房型Id  
 * @param  int   $detail       详情
 * @param  int   $startdate    售卖开始时间
 * @param  int   $enddate      售卖结束时间(可以为空)
 * @param  int   $pricetype    价格类型 1=>默认价格 2=>门市价 3=>微预定代销价 4=>尾房特卖 5=>钟点房价 6=>长租房价 7=>义卖价
 * @param  int   $from         来源 app还是网页还是其他？ 0=>网页 1=>App(可以为空)
 * @return mix                 成功返回新增Id,错误返回false
 */
function priceChangeLog($hotelId, $roomType, $detail, $startdate, $enddate, $pricetype, $from) {
    $priceRecordModel = D('PriceRecord');
    $result = $priceRecordModel->addInfo($hotelId, $roomType, $detail, $startdate, $enddate, $pricetype, $from);
    return $result;
}


function sendTcpClientMsg($userId, $cmd, $args)
{
    $msgPacket['user'] = $userId;
    $msgPacket['msg'] = array(
            'cmd' => $cmd,
            'args' => $args
    );
    $redis = new \Redis();
    $redis->connect(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'), 30);
    $redis->auth(C('REDIS_AUTH_PASSWORD'));
    $redis->select(11);
    $redis->rPush("socket_message", json_encode($msgPacket, JSON_UNESCAPED_UNICODE));
}

function checkClientLogin($userId)
{
    $redis = new \Redis();
    $redis->connect(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'), 30);
    $redis->auth(C('REDIS_AUTH_PASSWORD'));
    $redis->select(11);
    $fd = $redis->Get("socket_user_connection:$userId");
    return $fd?true:false;
}

function sendWebsocketMsg($webId, $cmd, $args)
{
    $msgPacket['webId'] = $webId;
    $msgPacket['msg'] = array(
        'cmd' => $cmd,
        'args' => $args
    );
    $redis = new \Redis();
    $redis->connect(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'), 30);
    $redis->auth(C('REDIS_AUTH_PASSWORD'));
    $redis->select(14);
    $redis->rPush("socket_message", json_encode($msgPacket, JSON_UNESCAPED_UNICODE));
}

/**
 * 以二维数组的某一列的值作为key，转为关联数组。关联数组的值为“key所在行”或“key所在行某列的值”。“key所在行某列的值”：由第三个参数指定列
 * key列必须唯一，如果不唯一，只返回第一次出现的行
 * @param array $dyadicArary 要转换的二维数组
 * @param string $uniqueKey 二维数组列名
 * @return array 转换后的关联数组
 */
function toAssocArray($dyadicArary, $keyFieldName = 'id', $valueFieldName = ''){
    if (! is_array($dyadicArary)) {
        return array();
    }
    $firstRow = current($dyadicArary);
    if (! isset($firstRow[$keyFieldName])) {
        return array();
    }
    $result = array();
    foreach ($dyadicArary as $row) {
        $key = $row[$keyFieldName];
        if (! isset($result[$key])) {
            if (!empty($valueFieldName) && isset($row[$valueFieldName])) {
                $result[$key] = $row[$valueFieldName];
            } else {
                $result[$key] = $row;
            }
        }
    }
    return $result;
}
/**
 * 将二维数组按某一列分组
 *
 * @param array $dyadicArary
 * @param string $uniqueKey
 * @return array 转换后的分组数组
 */
function toGroupArray($dyadicArary, $keyFieldName = 'id')
{
    if (! is_array($dyadicArary)) {
        return array();
    }
    $firstRow = current($dyadicArary);
    if (! isset($firstRow[$keyFieldName])) {
        return array();
    }
    $result = array();
    foreach ($dyadicArary as $row) {
        $key = $row[$keyFieldName];
        unset($row[$keyFieldName]);
        $result[$key][] = $row;
    }
    return $result;
}